/**
 * 统一权限管理工具
 * 管理应用所需的所有权限：定位、麦克风、语音识别
 */

import { Platform, PermissionsAndroid } from 'react-native';
import { PERMISSIONS, request, check, RESULTS } from 'react-native-permissions';
import AsyncStorage from '@react-native-async-storage/async-storage';

const PERMISSIONS_ASKED_FLAG = 'asked_app_permissions';

/**
 * 检查所有必需权限的状态
 * @returns {Promise<{location: boolean, microphone: boolean, speechRecognition: boolean}>}
 */
export async function checkAllPermissions() {
  const permissions = {
    location: false,
    microphone: false,
    speechRecognition: false,
  };

  try {
    if (Platform.OS === 'android') {
      // Android 权限检查
      const locationStatus = await PermissionsAndroid.check(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      );
      const microphoneStatus = await PermissionsAndroid.check(
        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
      );

      permissions.location = locationStatus;
      permissions.microphone = microphoneStatus;
      permissions.speechRecognition = microphoneStatus; // Android 语音识别使用麦克风权限
    } else if (Platform.OS === 'ios') {
      // iOS 权限检查
      const locationStatus = await check(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
      const microphoneStatus = await check(PERMISSIONS.IOS.MICROPHONE);
      const speechStatus = await check(PERMISSIONS.IOS.SPEECH_RECOGNITION);

      permissions.location = locationStatus === RESULTS.GRANTED;
      permissions.microphone = microphoneStatus === RESULTS.GRANTED;
      permissions.speechRecognition = speechStatus === RESULTS.GRANTED;
    }
  } catch (error) {
    console.error('检查权限失败:', error);
  }

  return permissions;
}

/**
 * 请求所有必需权限
 * @returns {Promise<{success: boolean, granted: {location: boolean, microphone: boolean, speechRecognition: boolean}}>}
 */
export async function requestAllPermissions() {
  const granted = {
    location: false,
    microphone: false,
    speechRecognition: false,
  };

  try {
    if (Platform.OS === 'android') {
      // Android 批量请求权限
      const results = await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
      ]);

      granted.location =
        results[PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION] ===
          PermissionsAndroid.RESULTS.GRANTED ||
        results[PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION] ===
          PermissionsAndroid.RESULTS.GRANTED;
      granted.microphone =
        results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] ===
        PermissionsAndroid.RESULTS.GRANTED;
      granted.speechRecognition = granted.microphone; // Android 语音识别使用麦克风权限
    } else if (Platform.OS === 'ios') {
      // iOS 逐个请求权限
      const locationResult = await request(
        PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
      );
      granted.location = locationResult === RESULTS.GRANTED;

      const microphoneResult = await request(PERMISSIONS.IOS.MICROPHONE);
      granted.microphone = microphoneResult === RESULTS.GRANTED;

      const speechResult = await request(PERMISSIONS.IOS.SPEECH_RECOGNITION);
      granted.speechRecognition = speechResult === RESULTS.GRANTED;
    }
  } catch (error) {
    console.error('请求权限失败:', error);
  }


  // 如果至少有一个权限被授予，就认为成功
  const success =
    granted.location || granted.microphone || granted.speechRecognition;

  return { success, granted };
}

/**
 * 检查是否已询问过应用权限
 * @returns {Promise<boolean>}
 */
export async function hasAskedPermissions() {
  try {
    const asked = await AsyncStorage.getItem(PERMISSIONS_ASKED_FLAG);
    return !!asked;
  } catch (error) {
    console.error('检查权限询问标记失败:', error);
    return false;
  }
}

/**
 * 标记已询问过应用权限
 * @returns {Promise<void>}
 */
export async function markPermissionsAsked() {
  try {
    await AsyncStorage.setItem(PERMISSIONS_ASKED_FLAG, '1');
  } catch (error) {
    console.error('保存权限询问标记失败:', error);
  }
}

/**
 * 检查特定权限是否已授予
 * @param {'location' | 'microphone' | 'speechRecognition'} permissionType
 * @returns {Promise<boolean>}
 */
export async function checkPermission(permissionType) {
  try {
    if (Platform.OS === 'android') {
      switch (permissionType) {
        case 'location':
          return await PermissionsAndroid.check(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          );
        case 'microphone':
        case 'speechRecognition':
          return await PermissionsAndroid.check(
            PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
          );
        default:
          return false;
      }
    } else if (Platform.OS === 'ios') {
      let status;
      switch (permissionType) {
        case 'location':
          status = await check(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
          break;
        case 'microphone':
          status = await check(PERMISSIONS.IOS.MICROPHONE);
          break;
        case 'speechRecognition':
          status = await check(PERMISSIONS.IOS.SPEECH_RECOGNITION);
          break;
        default:
          return false;
      }
      return status === RESULTS.GRANTED;
    }
  } catch (error) {
    console.error(`检查 ${permissionType} 权限失败:`, error);
    return false;
  }

  return false;
}

/**
 * 请求特定权限
 * @param {'location' | 'microphone' | 'speechRecognition'} permissionType
 * @returns {Promise<boolean>}
 */
export async function requestPermission(permissionType) {
  try {
    if (Platform.OS === 'android') {
      let permission;
      switch (permissionType) {
        case 'location':
          permission = PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION;
          break;
        case 'microphone':
        case 'speechRecognition':
          permission = PermissionsAndroid.PERMISSIONS.RECORD_AUDIO;
          break;
        default:
          return false;
      }
      const result = await PermissionsAndroid.request(permission);
      return result === PermissionsAndroid.RESULTS.GRANTED;
    } else if (Platform.OS === 'ios') {
      let permission;
      switch (permissionType) {
        case 'location':
          permission = PERMISSIONS.IOS.LOCATION_WHEN_IN_USE;
          break;
        case 'microphone':
          permission = PERMISSIONS.IOS.MICROPHONE;
          break;
        case 'speechRecognition':
          permission = PERMISSIONS.IOS.SPEECH_RECOGNITION;
          break;
        default:
          return false;
      }
      const result = await request(permission);
      return result === RESULTS.GRANTED;
    }
  } catch (error) {
    console.error(`请求 ${permissionType} 权限失败:`, error);
    return false;
  }

  return false;
}

